package com.etonenet.base.controller;

import java.security.Principal;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/user")
public class UserDetailController {
	
	private static Logger logger = LoggerFactory.getLogger(UserDetailController.class);
	
	/**
	 * 
	 * @param principal security 当前用户
	 * @return
	 */
	@RequestMapping
	public ModelAndView view(Principal principal) {
		if(principal!=null){
			System.out.println(principal.getName());
		}
		
		SecurityContext context = SecurityContextHolder.getContext();
		System.out.println(context.getAuthentication().getPrincipal());
		Map<String, Object> model = new HashMap<>();
		
		if(context.getAuthentication().getPrincipal() instanceof UserDetails){
			UserDetails userDetails = (UserDetails) context.getAuthentication().getPrincipal();
			Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
			for (Iterator<?> iterator = authorities.iterator(); iterator.hasNext();) {
				GrantedAuthority grantedAuthority = (GrantedAuthority) iterator.next();
				logger.info("user authorities:{}",grantedAuthority.getAuthority());
			}
			
			model.put("userDetails", userDetails);
		}
		
		return new ModelAndView("user/view", model);
	}
	
}
